package vip.liux.front.infrastructure.tenant;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

import static vip.liux.front.infrastructure.tenant.TenantContext.TENANT_ID;

public class TenantFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String tenantId = req.getHeader(TENANT_ID);
        TenantContext.setCurrentTenant(tenantId);
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            TenantContext.setCurrentTenant("");
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
